using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CR.Domain.DbContext;
using CR.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace CR.Infrastructure.Repositories
{
    /// <summary>
    /// 溯源管理仓储实现类
    /// </summary>
    public class TraceabilityRepository : BaseRepository<TraceabilityManagement>, ITraceabilityRepository
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public TraceabilityRepository(TraceabilityDbContext context) : base(context)
        {
        }

        /// <inheritdoc/>
        public async Task<TraceabilityManagement> GetByTraceabilityCodeAsync(string traceabilityCode)
        {
            return await _dbSet
                .Where(t => t.IsDeleted == 0)
                .FirstOrDefaultAsync(t => t.TraceabilityCode == traceabilityCode);
        }

        /// <inheritdoc/>
        public async Task<bool> ExistsTraceabilityCodeAsync(string traceabilityCode)
        {
            return await _dbSet
                .Where(t => t.IsDeleted == 0)
                .AnyAsync(t => t.TraceabilityCode == traceabilityCode);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<TraceabilityManagement>> GetAllActiveAsync()
        {
            return await _dbSet
                .Where(t => t.IsDeleted == 0)
                .OrderByDescending(t => t.CreateTime)
                .ToListAsync();
        }

        /// <inheritdoc/>
        public async Task<(IEnumerable<TraceabilityManagement> Data, int Total)> GetPagedTraceabilityAsync(
            int pageIndex,
            int pageSize,
            string productName = null,
            DateTime? productionBatchStart = null,
            DateTime? productionBatchEnd = null,
            int? shelfLifeMin = null,
            int? shelfLifeMax = null,
            string productionLicenseNumber = null,
            string productionCompany = null)
        {
            // 构建查询
            var query = _dbSet.Where(t => t.IsDeleted == 0);

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(productName))
                query = query.Where(t => t.ProductName.Contains(productName));

            if (productionBatchStart.HasValue)
                query = query.Where(t => t.ProductionBatch >= productionBatchStart.Value);

            if (productionBatchEnd.HasValue)
                query = query.Where(t => t.ProductionBatch <= productionBatchEnd.Value);

            if (shelfLifeMin.HasValue)
                query = query.Where(t => t.ShelfLife >= shelfLifeMin.Value);

            if (shelfLifeMax.HasValue)
                query = query.Where(t => t.ShelfLife <= shelfLifeMax.Value);

            if (!string.IsNullOrWhiteSpace(productionLicenseNumber))
                query = query.Where(t => t.ProductionLicenseNumber.Contains(productionLicenseNumber));

            if (!string.IsNullOrWhiteSpace(productionCompany))
                query = query.Where(t => t.ProductionCompany.Contains(productionCompany));

            // 获取总数
            var total = await query.CountAsync();

            // 排序并获取分页数据
            var data = await query
                .OrderByDescending(t => t.CreateTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (data, total);
        }

        /// <inheritdoc/>
        public async Task<bool> BatchDeleteAsync(IEnumerable<int> ids)
        {
            try
            {
                // 查询需要删除的实体
                var entities = await _dbSet
                    .Where(t => ids.Contains(t.Id))
                    .ToListAsync();

                if (!entities.Any())
                    return false;

                // 逻辑删除
                foreach (var entity in entities)
                {
                    entity.IsDeleted = 1;
                    entity.UpdateTime = DateTime.Now;
                }

                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <inheritdoc/>
        public async Task<bool> UpdateCompletenessScoreAsync(int id, int score)
        {
            var entity = await _dbSet.FindAsync(id);
            if (entity == null || entity.IsDeleted == 1)
                return false;

            entity.CompletenessScore = score;
            entity.UpdateTime = DateTime.Now;
            await _context.SaveChangesAsync();

            return true;
        }

        /// <summary>
        /// 重写添加方法，自动计算完善度评分
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>添加的实体</returns>
        public override async Task<TraceabilityManagement> AddAsync(TraceabilityManagement entity)
        {
            entity.CompletenessScore = CalculateCompletenessScore(entity);
            return await base.AddAsync(entity);
        }

        /// <summary>
        /// 重写更新方法，自动更新完善度评分和更新时间
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>更新的实体</returns>
        public override async Task<TraceabilityManagement> UpdateAsync(TraceabilityManagement entity)
        {
            entity.CompletenessScore = CalculateCompletenessScore(entity);
            entity.UpdateTime = DateTime.Now;
            return await base.UpdateAsync(entity);
        }

        /// <summary>
        /// 计算完善度评分
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>完善度评分</returns>
        private int CalculateCompletenessScore(TraceabilityManagement entity)
        {
            int score = 0;

            // 基础信息评分（最高50分）
            if (!string.IsNullOrWhiteSpace(entity.TraceabilityCode)) score += 10;
            if (!string.IsNullOrWhiteSpace(entity.ProductName)) score += 10;
            if (!string.IsNullOrWhiteSpace(entity.ProductionLicenseNumber)) score += 10;
            if (!string.IsNullOrWhiteSpace(entity.ProductionCompany)) score += 10;
            if (entity.ShelfLife > 0) score += 10;

            // 附加信息评分（最高50分）
            if (!string.IsNullOrWhiteSpace(entity.CoverImage)) score += 25;
            
            // 其他评分规则可以根据实际业务扩展...

            return score;
        }
    }
} 